from django.template import Library
from django.conf import settings
from django.urls import reverse

register = Library()


@register.inclusion_tag('rbac/static_menu.html')
def static_menu(request):
    """
    创建一级菜单
    :return:
    """
    menu_list = request.session[settings.PERMISSION_MENU_SESSION_KEY]
    return {'menu_list': menu_list}  # 返回给static_menu模板中的变量使用


@register.inclusion_tag('rbac/multi_menu.html')
def multi_menu(request):
    """
    显示二级菜单
    :param request:
    :return:
    """
    menu_dic = request.session[settings.PERMISSION_MENU_SESSION_KEY]
    print(menu_dic)
    return {'menu_dic': menu_dic}


@register.filter
def has_permission(request, alias):
    """权限按钮控制粒度"""
    if alias in request.session[settings.PERMISSION_SESSION_KEY]:
        return True


@register.simple_tag
def memory_url(request, name, *args, **kwargs):
    """
    保留一级菜单点击后的原搜索路径
    :param request: 接收get的值
    :param name: 反向生成url
    :return:
    """
    basic_url = reverse(name,args=args,kwargs=kwargs)  # /menu/add
    if not request.GET:  # 表示当前url无参数
        return basic_url
    from django.http import QueryDict
    old_params = request.GET.urlencode()  # 获取get的请求体值 mid=1
    query_dic = QueryDict(mutable=True)
    query_dic['_filter'] = old_params
    # query_dic.urlencode() # _filter=mid=1&aa=bb  自动转移
    return "%s?%s" % (basic_url, query_dic.urlencode())
